package com.company.project.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.company.project.common.pojo.AjaxResult;
import com.company.project.common.utils.AppUtil;
import com.company.project.common.pojo.ServiceCode;


/**
 * 文件上传的Controller
 */
@Api(value = "上传文件",tags = "上传文件")
@Controller("UploadController")
@RequestMapping("/fileUpload")
@Scope("prototype")
public class UploadController {

    private static final Log LOG = LogFactory.getLog(UploadController.class);
    @Value("${server.port}")
    private String port;
    @Value("${file-path}")
    private String filePath;

	/**
	 * 多文件上传 主要是使用了MultipartHttpServletRequest和MultipartFile
	 */
    @ApiOperation(value = "批量上传文件")
    @ApiImplicitParams({
        @ApiImplicitParam(value = "标题", name = "contradictionName", required = true),
        @ApiImplicitParam(value = "文件", name = "files", required = true)
    })
	@RequestMapping(value = "/upload/batch", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult batchUpload(@RequestParam("contradictionName") String contradictionName, @RequestParam("files") MultipartFile[] files) {
        if (files == null || files.length < 1) {
            return AppUtil.ajaxResult(ServiceCode.CODE_403, "缺少[files]参数,或为空!");
        }
        if (contradictionName == null || contradictionName.equals("")) {
            return AppUtil.ajaxResult(ServiceCode.CODE_403, "请先写好标题");
        }
//        if(type == null || type.equals("")){
//            return AppUtil.ajaxResult(ServiceCode.CODE_403, "type不能为空!");
//        }
//        if( !type.equals("img") && !type.equals("audio") && !type.equals("file") && !type.equals("video") ){
//            return AppUtil.ajaxResult(ServiceCode.CODE_403, "type只能为img、audio、file、video");
//        }
//        LOG.info("-------------上传文件------------"+type);
        String[] reUrl = new String[files.length];
        for (int i = 0; i < files.length; i++) {
            MultipartFile multipartFile = files[i];
            LOG.info("-------------文件------------" + i + "：" + multipartFile.getOriginalFilename());

            //文件后缀名
//            String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().indexOf("."));
            //文件新名称
            String newFileName = String.valueOf(System.currentTimeMillis() + (int) ((Math.random() * 9 + 1) * 100)) + "@_@" + multipartFile.getOriginalFilename();
            //中间目录
            String datePath = DateFormatUtils.format(new Date(), "yyyy-MM-dd") + File.separator;
            //全目录
            String fileFullName = filePath + datePath + contradictionName + File.separator + newFileName;
            // 图片访问地址（tomcat服务器）
            reUrl[i] = datePath + contradictionName + File.separator + newFileName;
            try {
                File file = new File(fileFullName);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(fileFullName)));
                out.write(multipartFile.getBytes());
                out.flush();
                out.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return AppUtil.ajaxResult(ServiceCode.CODE_200, "成功", reUrl);
	}

}